This lesson is adapted from the Data Carpentry Ecology Lesson
This is an R Markdown Notebook. When you execute code within the notebook, the results appear beneath the code.
Execute code chunks by clicking the Run button within the chunk or by placing your cursor inside it and pressing Cmd+Shift+Enter.
Add a new chunk by clicking the Insert Chunk button on the toolbar or by pressing Cmd+Option+I.
When you save the notebook, an HTML file containing the code and output will be saved alongside it (click the Preview button or press Cmd+Shift+K to preview the HTML file).
The preview shows you a rendered HTML copy of the contents of the editor. Consequently, unlike Knit, Preview does not run any R code chunks. Instead, the output of the chunk when it was last run in the editor is displayed.
We are studying the species repartition and weight of animals caught in plots in our study area. The dataset is stored as a comma separated value (CSV) file. Each row holds information for a single animal, and the columns represent:
| Column | Description |
|---|---|
| record_id | Unique id for the observation |
| month | month of observation |
| day | day of observation |
| year | year of observation |
| plot_id | ID of a particular plot |
| species_id | 2-letter code |
| sex | sex of animal (“M”, “F”) |
| hindfoot_length | length of the hindfoot in mm |
| weight | weight of the animal in grams |
| genus | genus of animal |
| species | species of animal |
| taxon | e.g. Rodent, Reptile, Bird, Rabbit |
| plot_type | type of plot |
We are going to use the R function download.file() to download the CSV file that contains the survey data from Figshare. Inside the download.file command, the first entry is a character string with the source URL (“https://ndownloader.figshare.com/files/2292169”). This source URL downloads a CSV file from figshare. The text after the comma (“data_raw/portal_data_joined.csv”) is the destination of the file on your local machine. You’ll need to have a folder on your machine called “data_raw” where you’ll download the file. So this command downloads a file from Figshare, names it “portal_data_joined.csv” and adds it to a preexisting folder named “data_raw”.
download.file(url = "https://ndownloader.figshare.com/files/2292169",
destfile = "data_raw/portal_data_joined.csv")
dplyr and tidyrdplyr is a package for making tabular data manipulation easier. It pairs nicely with tidyr which enables you to swiftly convert between different data formats for plotting and analysis.
Packages in R are basically sets of additional functions that let you do more stuff. The functions we’ve been using so far, like length() or mean(), come built into R; packages give you access to more of them. Before you use a package for the first time you need to install it on your machine, and then you should import it in every subsequent R session when you need it. You should already have installed the tidyverse package. This is an “umbrella-package” that installs several packages useful for data analysis which work together well such as tidyr, dplyr, ggplot2, tibble, etc.
The tidyverse package tries to address 3 common issues that arise when doing data analysis with some of the functions that come with R:
If we haven’t already done so, we can type install.packages("tidyverse") straight into the console. In fact, it’s better to write this in the console than in our script for any package, as there’s no need to re-install packages every time we run the script.
Then, to load the package type:
## load the tidyverse packages, incl. dplyr
library(tidyverse)
## ── Attaching packages ───────────────────────────────────── tidyverse 1.2.1 ──
## ✔ ggplot2 3.1.0 ✔ purrr 0.2.5
## ✔ tibble 2.0.0 ✔ dplyr 0.7.8
## ✔ tidyr 0.8.2 ✔ stringr 1.3.1
## ✔ readr 1.1.1 ✔ forcats 0.3.0
## Warning: package 'tibble' was built under R version 3.5.2
## ── Conflicts ──────────────────────────────────────── tidyverse_conflicts() ──
## ✖ dplyr::filter() masks stats::filter()
## ✖ dplyr::lag() masks stats::lag()
dplyr and tidyr?The package dplyr provides easy tools for the most common data manipulation tasks. It is built to work directly with data frames, with many common tasks optimized by being written in a compiled language (C++). An additional feature is the ability to work directly with data stored in an external database. The benefits of doing this are that the data can be managed natively in a relational database, queries can be conducted on that database, and only the results of the query are returned.
This addresses a common problem with R in that all operations are conducted in-memory and thus the amount of data you can work with is limited by available memory. The database connections essentially remove that limitation in that you can connect to a database of many hundreds of GB, conduct queries on it directly, and pull back into R only what you need for analysis.
The package tidyr addresses the common problem of wanting to reshape your data for plotting and use by different R functions. Sometimes we want data sets where we have one row per measurement. Sometimes we want a data frame where each measurement type has its own column, and rows are instead more aggregated groups - like plots or aquaria. Moving back and forth between these formats is non-trivial, and tidyr gives you tools for this and more sophisticated data manipulation.
To learn more about dplyr and tidyr after the workshop, you may want to check out this handy data transformation with dplyr cheatsheet and this one about tidyr.
We’ll read in our data using the read_csv() function, from the tidyverse package readr.
surveys <- read_csv("data_raw/portal_data_joined.csv")
## Parsed with column specification:
## cols(
## record_id = col_integer(),
## month = col_integer(),
## day = col_integer(),
## year = col_integer(),
## plot_id = col_integer(),
## species_id = col_character(),
## sex = col_character(),
## hindfoot_length = col_integer(),
## weight = col_integer(),
## genus = col_character(),
## species = col_character(),
## taxa = col_character(),
## plot_type = col_character()
## )
You will see the message Parsed with column specification, followed by each column name and its data type. When you execute read_csv on a data file, it looks through the first 1000 rows of each column and guesses the data type for each column as it reads it into R. For example, in this dataset, read_csv reads weight as col_double (a numeric data type), and species as col_character. You have the option to specify the data type for a column manually by using the col_types argument in read_csv.
## inspect the data
str(surveys)
## Classes 'tbl_df', 'tbl' and 'data.frame': 34786 obs. of 13 variables:
## $ record_id : int 1 72 224 266 349 363 435 506 588 661 ...
## $ month : int 7 8 9 10 11 11 12 1 2 3 ...
## $ day : int 16 19 13 16 12 12 10 8 18 11 ...
## $ year : int 1977 1977 1977 1977 1977 1977 1977 1978 1978 1978 ...
## $ plot_id : int 2 2 2 2 2 2 2 2 2 2 ...
## $ species_id : chr "NL" "NL" "NL" "NL" ...
## $ sex : chr "M" "M" NA NA ...
## $ hindfoot_length: int 32 31 NA NA NA NA NA NA NA NA ...
## $ weight : int NA NA NA NA NA NA NA NA 218 NA ...
## $ genus : chr "Neotoma" "Neotoma" "Neotoma" "Neotoma" ...
## $ species : chr "albigula" "albigula" "albigula" "albigula" ...
## $ taxa : chr "Rodent" "Rodent" "Rodent" "Rodent" ...
## $ plot_type : chr "Control" "Control" "Control" "Control" ...
## - attr(*, "spec")=List of 2
## ..$ cols :List of 13
## .. ..$ record_id : list()
## .. .. ..- attr(*, "class")= chr "collector_integer" "collector"
## .. ..$ month : list()
## .. .. ..- attr(*, "class")= chr "collector_integer" "collector"
## .. ..$ day : list()
## .. .. ..- attr(*, "class")= chr "collector_integer" "collector"
## .. ..$ year : list()
## .. .. ..- attr(*, "class")= chr "collector_integer" "collector"
## .. ..$ plot_id : list()
## .. .. ..- attr(*, "class")= chr "collector_integer" "collector"
## .. ..$ species_id : list()
## .. .. ..- attr(*, "class")= chr "collector_character" "collector"
## .. ..$ sex : list()
## .. .. ..- attr(*, "class")= chr "collector_character" "collector"
## .. ..$ hindfoot_length: list()
## .. .. ..- attr(*, "class")= chr "collector_integer" "collector"
## .. ..$ weight : list()
## .. .. ..- attr(*, "class")= chr "collector_integer" "collector"
## .. ..$ genus : list()
## .. .. ..- attr(*, "class")= chr "collector_character" "collector"
## .. ..$ species : list()
## .. .. ..- attr(*, "class")= chr "collector_character" "collector"
## .. ..$ taxa : list()
## .. .. ..- attr(*, "class")= chr "collector_character" "collector"
## .. ..$ plot_type : list()
## .. .. ..- attr(*, "class")= chr "collector_character" "collector"
## ..$ default: list()
## .. ..- attr(*, "class")= chr "collector_guess" "collector"
## ..- attr(*, "class")= chr "col_spec"
## preview the data
View(surveys)
Notice that the class of the data is now tbl_df
This is referred to as a “tibble”, the data structure is very similar to a data frame.
We’re going to learn some of the most common dplyr functions:
select(): subset columnsfilter(): subset rows on conditionsmutate(): create new columns by using information from other columnsgroup_by() and summarize(): create summary statistics on grouped dataarrange(): sort resultscount(): count discrete valuesTo select columns of a data frame, use select(). The first argument to this function is the data frame (surveys), and the subsequent arguments are the columns to keep.
select(surveys, plot_id, species_id, weight)
To select all columns except certain ones, put a “-” in front of the variable to exclude it.
select(surveys, -record_id, -species_id)
This will select all the variables in surveys except record_id and species_id.
To choose rows based on a specific criterion, use filter():
filter(surveys, year == 1995)
What if you want to select and filter at the same time? There are three ways to do this: use intermediate steps, nested functions, or pipes.
With intermediate steps, you create a temporary data frame and use that as input to the next function, like this:
surveys2 <- filter(surveys, weight < 5)
surveys_sml <- select(surveys2, species_id, sex, weight)
This is readable, but can clutter up your workspace with lots of objects that you have to name individually. With multiple steps, that can be hard to keep track of.
You can also nest functions (i.e. one function inside of another), like this:
surveys_sml <- select(filter(surveys, weight < 5), species_id, sex, weight)
This is handy, but can be difficult to read if too many functions are nested, as R evaluates the expression from the inside out (in this case, filtering, then selecting).
The last option, pipes, are a recent addition to R. Pipes let you take the output of one function and send it directly to the next, which is useful when you need to do many things to the same dataset. Pipes in R look like %>% and are made available via the magrittr package, installed automatically with dplyr. If you use RStudio, you can type the pipe with Ctrl + Shift + M if you have a PC or Cmd + Shift + M if you have a Mac.
surveys %>%
filter(weight < 5) %>%
select(species_id, sex, weight)
In the above code, we use the pipe to send the surveys dataset first through filter() to keep rows where weight is less than 5, then through select() to keep only the species_id, sex, and weight columns. Since %>% takes the object on its left and passes it as the first argument to the function on its right, we don’t need to explicitly include the data frame as an argument to the filter() and select() functions any more.
Some may find it helpful to read the pipe like the word “then”. For instance, in the above example, we took the data frame surveys, then we filtered for rows with weight < 5, then we selected columns species_id, sex, and weight. The dplyr functions by themselves are somewhat simple, but by combining them into linear workflows with the pipe, we can accomplish more complex manipulations of data frames.
If we want to create a new object with this smaller version of the data, we can assign it a new name:
surveys_sml <- surveys %>%
filter(weight < 5) %>%
select(species_id, sex, weight)
surveys_sml
Note that the final data frame is the leftmost part of this expression.
Frequently you’ll want to create new columns based on the values in existing columns, for example to do unit conversions, or to find the ratio of values in two columns. For this we’ll use mutate().
To create a new column of weight in kg:
surveys %>%
mutate(weight_kg = weight / 1000)
You can also create a second new column based on the first new column within the same call of mutate():
surveys %>%
mutate(weight_kg = weight / 1000,
weight_lb = weight_kg * 2.2)
If this runs off your screen and you just want to see the first few rows, you can use a pipe to view the head() of the data. (Pipes work with non-dplyr functions, too, as long as the dplyr or magrittr package is loaded).
surveys %>%
mutate(weight_kg = weight / 1000) %>%
head()
The first few rows of the output are full of NAs, so if we wanted to remove those we could insert a filter() in the chain:
surveys %>%
filter(!is.na(weight)) %>%
mutate(weight_kg = weight / 1000) %>%
head()
is.na() is a function that determines whether something is an NA. The ! symbol negates the result, so we’re asking for every row where weight is not an NA.
surveys data to include animals collected before 1995 and retain only the columns year, sex, and weight.surveys %>%
filter(year < 1995) %>%
select(year, sex, weight)
surveys data that meets the following criteria: contains only the species_id column and a new column called hindfoot_cm containing the hindfoot_length values converted to centimeters. In this hindfoot_cm column, there are no NAs and all values are less than 3.Hint: think about how the commands should be ordered to produce this data frame!
surveys_hindfoot_cm <- surveys %>%
filter(!is.na(hindfoot_length)) %>%
mutate(hindfoot_cm = hindfoot_length / 10) %>%
filter(hindfoot_cm < 3) %>%
select(species_id, hindfoot_cm)
summarize() functionMany data analysis tasks can be approached using the split-apply-combine paradigm: split the data into groups, apply some analysis to each group, and then combine the results. dplyr makes this very easy through the use of the group_by() function.
summarize() functiongroup_by() is often used together with summarize(), which collapses each group into a single-row summary of that group. group_by() takes as arguments the column names that contain the categorical variables for which you want to calculate the summary statistics. So to compute the mean weight by sex:
surveys %>%
group_by(sex) %>%
summarize(mean_weight = mean(weight, na.rm = TRUE))
You may also have noticed that the output from these calls doesn’t run off the screen anymore. It’s one of the advantages of tbl_df over data frame.
You can also group by multiple columns:
surveys %>%
group_by(sex, species_id) %>%
summarize(mean_weight = mean(weight, na.rm = TRUE)) %>%
tail()
Here, we used tail() to look at the last six rows of our summary. Before, we had used head() to look at the first six rows. We can see that the sex column contains NA values because some animals had escaped before their sex and body weights could be determined. The resulting mean_weight column does not contain NA but NaN (which refers to “Not a Number”) because mean() was called on a vector of NA values while at the same time setting na.rm = TRUE. To avoid this, we can remove the missing values for weight before we attempt to calculate the summary statistics on weight. Because the missing values are removed first, we can omit na.rm = TRUE when computing the mean:
surveys %>%
filter(!is.na(weight)) %>%
group_by(sex, species_id) %>%
summarize(mean_weight = mean(weight))
Here, again, the output from these calls doesn’t run off the screen anymore. If you want to display more data, you can use the print() function at the end of your chain with the argument n specifying the number of rows to display:
surveys %>%
filter(!is.na(weight)) %>%
group_by(sex, species_id) %>%
summarize(mean_weight = mean(weight)) %>%
print(n = 15)
## # A tibble: 64 x 3
## # Groups: sex [?]
## sex species_id mean_weight
## <chr> <chr> <dbl>
## 1 F BA 9.16
## 2 F DM 41.6
## 3 F DO 48.5
## 4 F DS 118.
## 5 F NL 154.
## 6 F OL 31.1
## 7 F OT 24.8
## 8 F OX 21
## 9 F PB 30.2
## 10 F PE 22.8
## 11 F PF 7.97
## 12 F PH 30.8
## 13 F PL 19.3
## 14 F PM 22.1
## 15 F PP 17.2
## # … with 49 more rows
Once the data are grouped, you can also summarize multiple variables at the same time (and not necessarily on the same variable). For instance, we could add a column indicating the minimum weight for each species for each sex:
surveys %>%
filter(!is.na(weight)) %>%
group_by(sex, species_id) %>%
summarize(mean_weight = mean(weight),
min_weight = min(weight))
It is sometimes useful to rearrange the result of a query to inspect the values. For instance, we can sort on min_weight to put the lighter species first:
surveys %>%
filter(!is.na(weight)) %>%
group_by(sex, species_id) %>%
summarize(mean_weight = mean(weight),
min_weight = min(weight)) %>%
arrange(min_weight)
To sort in descending order, we need to add the desc() function. If we want to sort the results by decreasing order of mean weight:
surveys %>%
filter(!is.na(weight)) %>%
group_by(sex, species_id) %>%
summarize(mean_weight = mean(weight),
min_weight = min(weight)) %>%
arrange(desc(mean_weight))
When working with data, we often want to know the number of observations found for each factor or combination of factors. For this task, dplyr provides count(). For example, if we wanted to count the number of rows of data for each sex, we would do:
surveys %>%
count(sex)
The count() function is shorthand for something we’ve already seen: grouping by a variable, and summarizing it by counting the number of observations in that group. In other words, surveys %>% count() is equivalent to:
surveys %>%
group_by(sex) %>%
summarise(count = n())
For convenience, count() provides the sort argument:
surveys %>%
count(sex, sort = TRUE)
Previous example shows the use of count() to count the number of rows/observations for one factor (i.e., sex). If we wanted to count combination of factors, such as sex and species, we would specify the first and the second factor as the arguments of count():
surveys %>%
count(sex, species)
With the above code, we can proceed with arrange() to sort the table according to a number of criteria so that we have a better comparison. For instance, we might want to arrange the table above in (i) an alphabetical order of the levels of the species and (ii) in descending order of the count:
surveys %>%
count(sex, species) %>%
arrange(species, desc(n))
From the table above, we may learn that, for instance, there are 75 observations of the albigula species that are not specified for its sex (i.e. NA).
plot_type surveyed?surveys %>%
count(plot_type)
group_by() and summarize() to find the mean, min, and max hindfoot length for each species (using species_id). Also add the number of observations (hint: see ?n).surveys %>%
filter(!is.na(hindfoot_length)) %>%
group_by(species_id) %>%
summarize(
mean_hindfoot_length = mean(hindfoot_length),
min_hindfoot_length = min(hindfoot_length),
max_hindfoot_length = max(hindfoot_length),
n = n()
)
year, genus, species_id, and weight.surveys %>%
filter(!is.na(weight)) %>%
group_by(year) %>%
filter(weight == max(weight)) %>%
select(year, genus, species, weight) %>%
arrange(year)
Now that you have learned how to use dplyr to extract information from or summarize your raw data, you may want to export these new data sets to share them with your collaborators or for archival.
Similar to the read_csv() function used for reading CSV files into R, there is a write_csv() function that generates CSV files from data frames.
Before using write_csv(), we are going to create a new folder, data, in our working directory that will store this generated dataset. We don’t want to write generated datasets in the same directory as our raw data. It’s good practice to keep them separate. The data_raw folder should only contain the raw, unaltered data, and should be left alone to make sure we don’t delete or modify it. In contrast, our script will generate the contents of the data directory, so even if the files it contains are deleted, we can always re-generate them.
In preparation for our next lesson on plotting, we are going to prepare a cleaned up version of the data set that doesn’t include any missing data.
Let’s start by removing observations of animals for which weight and hindfoot_length are missing, or the sex has not been determined:
surveys_complete <- surveys %>%
filter(!is.na(weight), # remove missing weight
!is.na(hindfoot_length), # remove missing hindfoot_length
!is.na(sex)) # remove missing sex
Because we are interested in plotting how species abundances have changed through time, we are also going to remove observations for rare species (i.e., that have been observed less than 50 times). We will do this in two steps: first we are going to create a data set that counts how often each species has been observed, and filter out the rare species; then, we will extract only the observations for these more common species:
## Extract the most common species_id
species_counts <- surveys_complete %>%
count(species_id) %>%
filter(n >= 50)
## Only keep the most common species
surveys_complete <- surveys_complete %>%
filter(species_id %in% species_counts$species_id)
### Create the dataset for exporting:
## Start by removing observations for which the `species_id`, `weight`,
## `hindfoot_length`, or `sex` data are missing:
surveys_complete <- surveys %>%
filter(species_id != "", # remove missing species_id
!is.na(weight), # remove missing weight
!is.na(hindfoot_length), # remove missing hindfoot_length
sex != "") # remove missing sex
## Now remove rare species in two steps. First, make a list of species which appear at least 50 times in our dataset:
species_counts <- surveys_complete %>%
count(species_id) %>%
filter(n >= 50) %>%
select(species_id)
## Second, keep only those species:
surveys_complete <- surveys_complete %>%
filter(species_id %in% species_counts$species_id)
To make sure that everyone has the same data set, check that surveys_complete has nrow(surveys_complete) rows and ncol(surveys_complete) columns by typing dim(surveys_complete).
Now that our data set is ready, we can save it as a CSV file in our data folder.
write_csv(surveys_complete, path = "data/surveys_complete.csv")
if (!dir.exists("data")) dir.create("data")
write_csv(surveys_complete, path = "data/surveys_complete.csv")
There are four rules defining a tidy dataset:
Here we examine the fourth rule: Each type of observational unit forms a table.
In surveys, the rows of surveys contain the values of variables associated with each record (the unit), values such as the weight or sex of each animal associated with each record. What if instead of comparing records, we wanted to compare the different mean weight of each genus between plots? (Ignoring plot_type for simplicity).
We’d need to create a new table where each row (the unit) is comprised of values of variables associated with each plot. In practical terms this means the values in genus would become the names of column variables and the cells would contain the values of the mean weight observed on each plot.
Having created a new table, it is therefore straightforward to explore the relationship between the weight of different genera within, and between, the plots. The key point here is that we are still following a tidy data structure, but we have reshaped the data according to the observations of interest: average genus weight per plot instead of recordings per date.
The opposite transformation would be to transform column names into values of a variable.
We can do both these of transformations with two tidyr functions, spread() and gather().
spread() takes three principal arguments:
Further arguments include fill which, if set, fills in missing values with the value provided.
Let’s use spread() to transform surveys to find the mean weight of each genus in each plot over the entire survey period. We use filter(), group_by() and summarise() to filter our observations and variables of interest, and create a new variable for the mean_weight.
surveys_gw <- surveys %>%
filter(!is.na(weight)) %>%
group_by(plot_id, genus) %>%
summarize(mean_weight = mean(weight))
str(surveys_gw)
## Classes 'grouped_df', 'tbl_df', 'tbl' and 'data.frame': 196 obs. of 3 variables:
## $ plot_id : int 1 1 1 1 1 1 1 1 2 2 ...
## $ genus : chr "Baiomys" "Chaetodipus" "Dipodomys" "Neotoma" ...
## $ mean_weight: num 7 22.2 60.2 156.2 27.7 ...
## - attr(*, "spec")=List of 2
## ..$ cols :List of 13
## .. ..$ record_id : list()
## .. .. ..- attr(*, "class")= chr "collector_integer" "collector"
## .. ..$ month : list()
## .. .. ..- attr(*, "class")= chr "collector_integer" "collector"
## .. ..$ day : list()
## .. .. ..- attr(*, "class")= chr "collector_integer" "collector"
## .. ..$ year : list()
## .. .. ..- attr(*, "class")= chr "collector_integer" "collector"
## .. ..$ plot_id : list()
## .. .. ..- attr(*, "class")= chr "collector_integer" "collector"
## .. ..$ species_id : list()
## .. .. ..- attr(*, "class")= chr "collector_character" "collector"
## .. ..$ sex : list()
## .. .. ..- attr(*, "class")= chr "collector_character" "collector"
## .. ..$ hindfoot_length: list()
## .. .. ..- attr(*, "class")= chr "collector_integer" "collector"
## .. ..$ weight : list()
## .. .. ..- attr(*, "class")= chr "collector_integer" "collector"
## .. ..$ genus : list()
## .. .. ..- attr(*, "class")= chr "collector_character" "collector"
## .. ..$ species : list()
## .. .. ..- attr(*, "class")= chr "collector_character" "collector"
## .. ..$ taxa : list()
## .. .. ..- attr(*, "class")= chr "collector_character" "collector"
## .. ..$ plot_type : list()
## .. .. ..- attr(*, "class")= chr "collector_character" "collector"
## ..$ default: list()
## .. ..- attr(*, "class")= chr "collector_guess" "collector"
## ..- attr(*, "class")= chr "col_spec"
## - attr(*, "vars")= chr "plot_id"
## - attr(*, "drop")= logi TRUE
This yields surveys_gw where the observations for each plot are spread across multiple rows, 196 observations of 3 variables. Using spread() to key on genus with values from mean_weight this becomes 24 observations of 11 variables, one row for each plot.
surveys_spread <- surveys_gw %>%
spread(key = genus, value = mean_weight)
str(surveys_spread)
## Classes 'grouped_df', 'tbl_df', 'tbl' and 'data.frame': 24 obs. of 11 variables:
## $ plot_id : int 1 2 3 4 5 6 7 8 9 10 ...
## $ Baiomys : num 7 6 8.61 NA 7.75 ...
## $ Chaetodipus : num 22.2 25.1 24.6 23 18 ...
## $ Dipodomys : num 60.2 55.7 52 57.5 51.1 ...
## $ Neotoma : num 156 169 158 164 190 ...
## $ Onychomys : num 27.7 26.9 26 28.1 27 ...
## $ Perognathus : num 9.62 6.95 7.51 7.82 8.66 ...
## $ Peromyscus : num 22.2 22.3 21.4 22.6 21.2 ...
## $ Reithrodontomys: num 11.4 10.7 10.5 10.3 11.2 ...
## $ Sigmodon : num NA 70.9 65.6 82 82.7 ...
## $ Spermophilus : num NA NA NA NA NA NA NA NA NA NA ...
## - attr(*, "vars")= chr "plot_id"
## - attr(*, "drop")= logi TRUE
## - attr(*, "indices")=List of 24
## ..$ : int 0
## ..$ : int 1
## ..$ : int 2
## ..$ : int 3
## ..$ : int 4
## ..$ : int 5
## ..$ : int 6
## ..$ : int 7
## ..$ : int 8
## ..$ : int 9
## ..$ : int 10
## ..$ : int 11
## ..$ : int 12
## ..$ : int 13
## ..$ : int 14
## ..$ : int 15
## ..$ : int 16
## ..$ : int 17
## ..$ : int 18
## ..$ : int 19
## ..$ : int 20
## ..$ : int 21
## ..$ : int 22
## ..$ : int 23
## - attr(*, "group_sizes")= int 1 1 1 1 1 1 1 1 1 1 ...
## - attr(*, "biggest_group_size")= int 1
## - attr(*, "labels")='data.frame': 24 obs. of 1 variable:
## ..$ plot_id: int 1 2 3 4 5 6 7 8 9 10 ...
## ..- attr(*, "vars")= chr "plot_id"
## ..- attr(*, "drop")= logi TRUE
We could now plot comparisons between the weight of genera in different plots, although we may wish to fill in the missing values first.
surveys_gw %>%
spread(genus, mean_weight, fill = 0) %>%
head()
The opposing situation could occur if we had been provided with data in the form of surveys_spread, where the genus names are column names, but we wish to treat them as values of a genus variable instead.
In this situation we are gathering the column names and turning them into a pair of new variables. One variable represents the column names as values, and the other variable contains the values previously associated with the column names.
gather() takes four principal arguments:
To recreate surveys_gw from surveys_spread we would create a key called genus and value called mean_weight and use all columns except plot_id for the key variable. Here we exclude plot_id from being gather()ed.
surveys_gather <- surveys_spread %>%
gather(key = "genus", value = "mean_weight", -plot_id)
str(surveys_gather)
## Classes 'grouped_df', 'tbl_df', 'tbl' and 'data.frame': 240 obs. of 3 variables:
## $ plot_id : int 1 2 3 4 5 6 7 8 9 10 ...
## $ genus : chr "Baiomys" "Baiomys" "Baiomys" "Baiomys" ...
## $ mean_weight: num 7 6 8.61 NA 7.75 ...
## - attr(*, "vars")= chr "plot_id"
## - attr(*, "drop")= logi TRUE
## - attr(*, "indices")=List of 24
## ..$ : int 0 24 48 72 96 120 144 168 192 216
## ..$ : int 1 25 49 73 97 121 145 169 193 217
## ..$ : int 2 26 50 74 98 122 146 170 194 218
## ..$ : int 3 27 51 75 99 123 147 171 195 219
## ..$ : int 4 28 52 76 100 124 148 172 196 220
## ..$ : int 5 29 53 77 101 125 149 173 197 221
## ..$ : int 6 30 54 78 102 126 150 174 198 222
## ..$ : int 7 31 55 79 103 127 151 175 199 223
## ..$ : int 8 32 56 80 104 128 152 176 200 224
## ..$ : int 9 33 57 81 105 129 153 177 201 225
## ..$ : int 10 34 58 82 106 130 154 178 202 226
## ..$ : int 11 35 59 83 107 131 155 179 203 227
## ..$ : int 12 36 60 84 108 132 156 180 204 228
## ..$ : int 13 37 61 85 109 133 157 181 205 229
## ..$ : int 14 38 62 86 110 134 158 182 206 230
## ..$ : int 15 39 63 87 111 135 159 183 207 231
## ..$ : int 16 40 64 88 112 136 160 184 208 232
## ..$ : int 17 41 65 89 113 137 161 185 209 233
## ..$ : int 18 42 66 90 114 138 162 186 210 234
## ..$ : int 19 43 67 91 115 139 163 187 211 235
## ..$ : int 20 44 68 92 116 140 164 188 212 236
## ..$ : int 21 45 69 93 117 141 165 189 213 237
## ..$ : int 22 46 70 94 118 142 166 190 214 238
## ..$ : int 23 47 71 95 119 143 167 191 215 239
## - attr(*, "group_sizes")= int 10 10 10 10 10 10 10 10 10 10 ...
## - attr(*, "biggest_group_size")= int 10
## - attr(*, "labels")='data.frame': 24 obs. of 1 variable:
## ..$ plot_id: int 1 2 3 4 5 6 7 8 9 10 ...
## ..- attr(*, "vars")= chr "plot_id"
## ..- attr(*, "drop")= logi TRUE
Note that now the NA genera are included in the re-gathered format. Spreading and then gathering can be a useful way to balance out a dataset so every replicate has the same composition.
We could also have used a specification for what columns to include. This can be useful if you have a large number of identifying columns, and it’s easier to specify what to gather than what to leave alone. And if the columns are directly adjacent, we don’t even need to list them all out - just use the : operator!
surveys_spread %>%
gather(key = "genus", value = "mean_weight", Baiomys:Spermophilus) %>%
head()
surveys data frame with year as columns, plot_id as rows, and the number of genera per plot as the values. You will need to summarize before reshaping, and use the function n_distinct() to get the number of unique genera within a particular chunk of data. It’s a powerful function! See ?n_distinct for more.surveys_spread_genera <- surveys %>%
group_by(plot_id, year) %>%
summarize(n_genera = n_distinct(genus)) %>%
spread(year, n_genera)
head(surveys_spread_genera)
gather() it again, so each row is a unique plot_id by year combination.surveys_spread_genera %>%
gather("year", "n_genera", -plot_id)
surveys data set has two measurement columns: hindfoot_length and weight.gather() to create a dataset where we have a key column called measurement and a value column that takes on the value of either hindfoot_length or weight. Hint: You’ll need to specify which columns are being gathered.surveys_long <- surveys %>%
gather("measurement", "value", hindfoot_length, weight)
measurement in each year for each different plot_type. Then spread() them into a data set with a column for hindfoot_length and weight. Hint: You only need to specify the key and value columns for spread().surveys_long %>%
group_by(year, measurement, plot_type) %>%
summarize(mean_value = mean(value, na.rm=TRUE)) %>%
spread(measurement, mean_value)